package cn.baiweigang.uu.service.fetch;

import cn.baiweigang.uu.db.dataobj.StockInfoDo;
import cn.baiweigang.uu.db.repository.HistoryDayInfoRepository;
import cn.baiweigang.uu.service.okhttp.HttpService;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
public class EastmoneyService extends FetchBaseService {

    @Autowired
    private HistoryDayInfoRepository historyDayInfoRepository;

    @Autowired
    private HttpService httpService;

    public void updateRank(String ds) {
        List<StockInfoDo> stockInfoDoList = historyDayInfoRepository.queryByDs(ds);
        if (stockInfoDoList==null || stockInfoDoList.size()<1){
            log.info("当天无股票数据，不需要拉取排名");
            return;
        }

        for (int i = 0; i < stockInfoDoList.size(); i++) {
            try {
                StockInfoDo stockInfoDo = historyDayInfoRepository.queryNewestByDm(stockInfoDoList.get(i).getDm());
                pullAndSaveRank(stockInfoDo);
                //暂停200毫秒 防止高并发
                Thread.sleep(200);
            } catch (Throwable e) {
                log.error("拉取异常 dm=" + stockInfoDoList.get(i).getDm() + " " + e.getMessage());
            }
        }
    }

    private void pullAndSaveRank(StockInfoDo stockInfoDo) {
        String url = "https://emappdata.eastmoney.com/stockrank/getCurrentLatest";
        String appId = "appId01";
        String globalId = "786e4c21-70dc-435a-93bb-38";
        String marketType = "";

        JSONObject request = new JSONObject();
        request.put("appId", appId);
        request.put("globalId", globalId);
        request.put("marketType", marketType);
        String pre = stockInfoDo.getDm().startsWith("6") ? "SH" : "SZ";
        request.put("srcSecurityCode", pre + stockInfoDo.getDm());

        JSONObject resp = JSONObject.parseObject(httpService.doPost(url, null, request));
        if (resp != null) {
            String pm = resp.getJSONObject("data").getString("rank");
            historyDayInfoRepository.updateRank(stockInfoDo.getId(), pm);
        }
    }


}
